import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Button, Space, Tag, message, Layout, Typography, Table, Modal, Form, Input, Select, Collapse } from 'antd';
import { EditOutlined, DeleteOutlined, ArrowLeftOutlined, PlusOutlined, DownOutlined } from '@ant-design/icons';
import { Vector, VectorStatus, Knowledge } from './store/vectorTypes';
import { vectorStore } from './store/vectorStore';
import { knowledgeStore } from './store/knowledgeStore';
import { knowledgeItemStore } from './store/knowledgeItemStore';
import VectorForm from './components/VectorForm';
import VectorItemModal from './components/VectorItemModal';

const { Title } = Typography;
const { Option } = Select;
const { Panel } = Collapse;

const VectorDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [vector, setVector] = useState<Vector | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [tables, setTables] = useState<Knowledge[]>([]);
  const [isTableModalVisible, setIsTableModalVisible] = useState(false);
  const [tableForm] = Form.useForm();

  // 知识条目弹窗相关状态
  const [isItemModalVisible, setIsItemModalVisible] = useState(false);
  const [currentTable, setCurrentTable] = useState<Knowledge | null>(null);

  // 新增：编辑表相关状态
  const [editingTable, setEditingTable] = useState<Knowledge | null>(null);

  useEffect(() => {
    const fetchVectors = async () => {
      await vectorStore.getVector(id);
      setVector(vectorStore.editingVector); // 创建新数组触发更新
      await knowledgeStore.fetchKnowledges(id);
      setTables(knowledgeStore.knowledges);
    };
    fetchVectors();
  }, []);

  const handleEdit = () => {
    setIsModalVisible(true);
  };

  const handleDelete = () => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除向量知识库"${vector?.name}"吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        vectorStore.deleteVector(vector.id);
        navigate('/engine/vector');
      },
    });
  };

  const handleSubmit = (values: any) => {
    setVector({ ...vector, ...values } as Vector);
    vectorStore.saveVector(values);
    setIsModalVisible(false);
  };

  const handleAddTable = () => {
    setIsTableModalVisible(true);
  };

  const handleEditTable = (table: Knowledge) => {
    setEditingTable(table);
    setIsTableModalVisible(true);
    // 表单赋值
    tableForm.setFieldsValue(table);
    // 修复：同步设置mobx store的editingKnowledge，保证saveKnowledge能识别编辑模式
    knowledgeStore.editingKnowledge = table;
  };

  const handleTableSubmit = (values: any) => {
    values.baseId = id;
    let newTable: Knowledge;
    if (editingTable) {
      // 编辑模式
      newTable = {
        ...editingTable,
        ...values,
      };
      knowledgeStore.saveKnowledge(newTable);
      setTables(tables.map(t => t.id === newTable.id ? newTable : t));
    } else {
      // 新建模式
      newTable = {
        ...values,
        itemCount: 0,
      };
      knowledgeStore.saveKnowledge(newTable);
      setTables([...tables, newTable]);
    }
    setIsTableModalVisible(false);
    setEditingTable(null);
    tableForm.resetFields();
    // 新建后清空editingKnowledge，防止影响下次编辑
    knowledgeStore.editingKnowledge = null;
  };

  // 处理查看条目
  const handleViewItems = (table: Knowledge) => {
    setCurrentTable(table);
    setIsItemModalVisible(true);
  };

  const columns = [
    {
      title: '表名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '表标识',
      dataIndex: 'collectionIdentifier',
      key: 'collectionIdentifier',
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      render: (type: number) => {
        const types = {
          0: { text: '主数据表', color: 'blue' },
          1: { text: '知识问答表', color: 'green' },
          2: { text: '元数据表', color: 'purple' },
        };
        const typeInfo = types[type as keyof typeof types] || { text: '未知', color: 'default' };
        return <Tag color={typeInfo.color}>{typeInfo.text}</Tag>;
      },
    },
    {
      title: '存储类型',
      dataIndex: 'metaStorageType',
      key: 'metaStorageType',
      render: (type: number) => (
        <Tag color={type === 0 ? 'blue' : 'green'}>
          {type === 1 ? '向量化' : '数据库'}
        </Tag>
      ),
    },
    {
      title: '向量模型',
      dataIndex: 'vectorModel',
      key: 'vectorModel',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '知识条目数量',
      dataIndex: 'itemCount',
      key: 'itemCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Knowledge) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEditTable(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleViewItems(record)}>
            查看条目
          </Button>
          <Button type="link" danger onClick={() => {
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除表"${record.name}"吗？`,
              onOk: () => {
                setTables(tables.filter(t => t.id !== record.id));
                knowledgeStore.deleteKnowledge(record.id);
              },
            });
          }}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  if (!vector) {
    return null;
  }

  return (
    <Layout style={{ padding: '24px' }}>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/engine/vector')} />
        <Title level={4} style={{ margin: 0 }}>{vector.name}</Title>
      </Space>

      <Collapse
        defaultActiveKey={[]}
        style={{ marginBottom: 24 }}
        expandIcon={({ isActive }) => <DownOutlined rotate={isActive ? 180 : 0} />}
      >
        <Panel
          header="知识库详情"
          key="1"
          extra={
            <Space size={2} onClick={e => e.stopPropagation()}>
              <Button
                type="text"
                icon={<EditOutlined />}
                onClick={handleEdit}
              />
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                onClick={handleDelete}
              />
            </Space>
          }
        >
          <Descriptions column={2}>
            <Descriptions.Item label="知识库ID">{vector.id}</Descriptions.Item>
            <Descriptions.Item label="知识库类型">
              <Tag color={
                vector.baseType === 'text' ? 'blue' :
                  vector.baseType === 'image' ? 'green' : 'purple'
              }>
                {vector.baseType === 'text' ? '文本' : vector.baseType === 'image' ? '图片' : '混合'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={vector.status === VectorStatus.ENABLED ? 'success' : 'default'}>
                {vector.status === VectorStatus.ENABLED ? '启用' : '禁用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="向量模型">{vector.vectorModel}</Descriptions.Item>
            <Descriptions.Item label="向量维度">{vector.dimension}</Descriptions.Item>
            <Descriptions.Item label="文件格式">
              {vector.fileFormat && vector.fileFormat.trim() !== '' && vector.fileFormat.split(',')?.map(format => (
                <Tag key={format} style={{ marginRight: 4 }}>{format.toUpperCase()}</Tag>
              ))}
            </Descriptions.Item>
            <Descriptions.Item label="切片策略">
              <Tag color={
                vector.splitStrategy === 0 ? 'blue' :
                  vector.splitStrategy === 1 ? 'green' : 'purple'
              }>
                {vector.splitStrategy === 0 ? '固定长度' :
                  vector.splitStrategy === 1 ? '语义分割' : '自定义'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="最大段落大小">{vector.maxParagraphSize}</Descriptions.Item>
            <Descriptions.Item label="最大重叠大小">{vector.maxOverlapSize}</Descriptions.Item>
            <Descriptions.Item label="标签">
              {vector.tags?.map(tag => (
                <Tag key={tag}>{tag}</Tag>
              ))}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{new Date(vector.createTime).toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{new Date(vector.updateTime).toLocaleString()}</Descriptions.Item>
          </Descriptions>
        </Panel>
      </Collapse>

      <Card
        title="知识库表"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddTable}>
            新建表
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={tables}
          rowKey="id"
          pagination={{
            total: tables.length,
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </Card>

      <Modal
        title="编辑向量知识库"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
        style={{ maxHeight: '80vh' }}
        bodyStyle={{
          maxHeight: 'calc(80vh - 108px)',
          overflowY: 'auto',
          padding: '24px'
        }}
      >
        <VectorForm
          initialValues={vector || undefined}
          onSubmit={handleSubmit}
          onCancel={() => setIsModalVisible(false)}
        />
      </Modal>

      <Modal
        title={editingTable ? '编辑表' : '新建表'}
        open={isTableModalVisible}
        onCancel={() => { setIsTableModalVisible(false); setEditingTable(null); tableForm.resetFields(); }}
        footer={null}
      >
        <Form
          form={tableForm}
          onFinish={handleTableSubmit}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="表名"
            rules={[
              { required: true, message: '请输入表名' },
              { max: 50, message: '表名长度不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入表名" />
          </Form.Item>
          <Form.Item
            name="collectionIdentifier"
            label="表标识"
            rules={[
              { required: true, message: '请输入表标识' },
              { max: 20, message: '表标识长度不能超过20个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '表标识只能包含字母、数字和下划线' }
            ]}
          >
            <Input placeholder="请输入表标识" />
          </Form.Item>
          <Form.Item
            name="businessType"
            label="业务类型"
            rules={[{ required: true, message: '请选择业务类型' }]}
          >
            <Select placeholder="请选择业务类型">
              <Option value={0}>主数据表</Option>
              <Option value={1}>知识问答表</Option>
              <Option value={2}>元数据表</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="metaStorageType"
            label="存储类型"
            rules={[{ required: true, message: '请选择存储类型' }]}
          >
            <Select placeholder="请选择存储类型">
              <Option value={0}>数据库</Option>
              <Option value={1}>向量化</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label="表描述"
          >
            <Input.TextArea placeholder="请输入表描述" rows={4} />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => { setIsTableModalVisible(false); setEditingTable(null); tableForm.resetFields(); }}>取消</Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 知识条目列表组件 */}
      <VectorItemModal
        visible={isItemModalVisible}
        onCancel={() => setIsItemModalVisible(false)}
        currentTable={currentTable}
        vector={vector}
      />
    </Layout>
  );
};

export default VectorDetail; 